package com.suhe.ozon.http;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.suhe.ozon.entity.dto.PriceUpdateDTO;
import com.suhe.ozon.entity.po.ClientPO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *     商品价格更新
 * </p>
 *
 * @author liuning
 * @date 17:26 2024/1/21
 */
@Slf4j
public class PriceUpdateHttp {

    private final static String UPDATE_PRICE_URL = "https://api-seller.ozon.ru/v1/product/import/prices";

    public Set<String> sync(ClientPO ozonClient, List<PriceUpdateDTO> productList) throws IOException {
        final CloseableHttpClient httpClient = HttpClients.createDefault();
        final HttpPost httpPost = new HttpPost(UPDATE_PRICE_URL);
        httpPost.addHeader("Client-Id", ozonClient.getClientId());
        httpPost.addHeader("Api-Key", ozonClient.getSecretKey());
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.addHeader("Host", "api-seller.ozon.ru");

        final ImmutableMap<String, List<Map<String, Object>>> params = ImmutableMap.of("prices", productList.stream().map(p -> {
            final Map<String, Object> map = Maps.newHashMap();
            map.put("product_id", p.getProductId());
            map.put("min_price", p.getMinPrice());
            map.put("price", p.getPrice());
            map.put("old_price", p.getOldPrice());
            map.put("price_strategy_enabled", p.getPriceStrategyEnabled());
            map.put("currency_code", p.getCurrencyCode());
            if (StrUtil.isNotBlank(p.getAutoActionEnabled())) {
                map.put("auto_action_enabled", p.getAutoActionEnabled());
            }
            return map;
        }).collect(Collectors.toList()));

        StringEntity stringEntity = new StringEntity(JSONUtil.toJsonStr(params));
        stringEntity.setContentEncoding("UTF-8");
        stringEntity.setContentType("application/json");
        httpPost.setEntity(stringEntity);

        final CloseableHttpResponse response = httpClient.execute(httpPost);if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            log.error("接口请求失败");
            return Collections.emptySet();
        }
        String result = EntityUtils.toString(response.getEntity());
        final JSONArray jsonArray = JSONUtil.parseObj(result).getJSONArray("result");
        return jsonArray.stream().filter(jsonObject -> ((JSONObject)jsonObject).getBool("updated")).map(jsonObject -> ((JSONObject)jsonObject).getStr("product_id")).collect(Collectors.toSet());
    }
}
